package com.bobo.util;

import com.bobo.annotations.Lst;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;


/**
 * Created by bobo on 2016/9/27.
 */
public class UploadFiles {

    private static String PATH = "/public/img/";

    /**
     * 提交的表单打包成map
     * @param request
     * @return
     * @throws IOException
     */
    public static Map<String, String[]> UploadForms(HttpServletRequest request) throws IOException {
        Map<String, String[]> map;
        request.setCharacterEncoding("utf-8");
        boolean isMultipart =  ServletFileUpload.isMultipartContent(request);
        if(isMultipart){
            map = upLoadFile(request);
        }else {
            map = request.getParameterMap();
        }
        return map;
    }
    public static Map<String, String[]> upLoadFile(HttpServletRequest request){
        Map<String, String[]> map = new HashMap<>();
        //为解析类提供配置信息
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建解析类的实例
        ServletFileUpload sfu = new ServletFileUpload(factory);
        //开始解析
        sfu.setFileSizeMax(1024 * 10240);
        //每个表单域中数据会封装到一个对应的FileItem对象上
        String fileName = null;
        try {
            List<FileItem> items = sfu.parseRequest(request);
            //区分表单域
            for (FileItem item : items) {
                //isFormField为true，表示这不是文件上传表单域
                if (!item.isFormField()) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
                    String today =  df.format(new java.util.Date());
                    String path = request.getSession().getServletContext().getRealPath(PATH) + today;
                    File file = new File(path);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    fileName = item.getName();
                    if (fileName == null||"".equals(fileName)) {
                        continue;
                    }
                    fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
                    file = new File(path + "/" + fileName);
                    if (!file.exists()) {
                        item.write(file);
                        //将上传图片的名字记录到数据库中
                    }
                    map.put(item.getFieldName(), new String[]{PATH + today + "/" + fileName});
                } else {
                    if (map.containsKey(item.getFieldName())) {
                        String[] vals = map.get(item.getFieldName());

                        vals = Arrays.copyOf(vals, vals.length + 1);
                        vals[vals.length - 1] = item.getString("utf-8");

                        map.put(item.getFieldName(), vals);
                    } else {
                        map.put(item.getFieldName(), new String[]{item.getString("utf-8")});
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
//    /**
//     * 组装对象
//     * @param map
//     * @param mp
//     * @return
//     */
//    private Map<String, Object> assemble(Map<String, String[]> map, Map<String, Class> mp) {
//        //返回的map
//        Map<String, Object> rsm = new HashMap<>();
//
//        try {
//            //表单提交的map
//            Set<String> parameterNames = map.keySet();
//            //参数map的keySet  参数注解的值 与表单的name比较
//            Set<String> names = mp.keySet();
//            for (String name : names) {
//                //参数map的值
//                Class clz = mp.get(name);
//                if (Utils.isModelC(clz)) {
//                    Object object = clz.newInstance();
//                    //遍历表单name集
//                    for (String parameterName : parameterNames) {
//                        //获取页面值
//                        String[] valss = map.get(parameterName);
//                        String vals = valss[0];
//                        //获取类的成员变量
//                        Field[] fields = clz.getDeclaredFields();
//                        for (Field f : fields) {
//                            //成员变量为模型类
//                            if (Utils.isModel(f)) {
//                                //模型类
//                                Class<?> cl = f.getType();
//                                Object o = cl.newInstance();
//                                this.fields(cl, name, parameterName, vals, object);
//                            } else
//                                if(f.getType().toString().contains("java.util.List")){
//                                    //判断页面上的name名称与成员变量名称是否一致
//                                    if ((name + "." + f.getName()).equals(parameterName)) {
//                                        if(f.isAnnotationPresent(Lst.class)){
//                                            Lst annotation = f.getAnnotation(Lst.class);
//                                            Class value = annotation.value();
//                                            List<Object> obs = new ArrayList<>();
//                                            String[] vs = map.get(parameterName);
//                                            for(String v:vs){
//                                                Object ob = value.newInstance();
//                                                Method setId = value.getDeclaredMethod("setId", Integer.class);
//                                                Object o = changeType(Integer.class, v);
//                                                setId.invoke(ob,o);
//                                                obs.add(ob);
//                                            }
//                                            //获取方法
//                                            Method method = clz.getDeclaredMethod("set" + Utils.captureName(f.getName()), f.getType());
//                                            //调用方法
//                                            method.invoke(object, obs);
//                                        }
//                                    }
//
//                            }else {
//                                //判断页面上的name名称与成员变量名称是否一致
//                                if ((name + "." + f.getName()).equals(parameterName)) {
//                                    //方法名
//                                    String methodName = "set" + Utils.captureName(f.getName());
//                                    //获取方法
//                                    Method method = clz.getDeclaredMethod(methodName, f.getType());
//                                    //转换成赋值需要的类型
//                                    Object o = this.changeType(f.getType(), vals);
//                                    //调用方法
//                                    method.invoke(object, o);
//                                }
//                            }
//                        }
//                    }
//                    rsm.put(name, object);
//                } else {
//                    for (String parameterName : parameterNames) {
//                        //获取页面值
//                        String[] valss = map.get(parameterName);
//                        String vals = valss[0];
//                        if (name.equals(parameterName)) {
//                            Object object = this.changeType(clz, vals);
//                            rsm.put(name, object);
//                        }
//                    }
//                }
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return rsm;
//    }




    //删除图片
    public static void delFile(HttpServletRequest request,  String path) {
        path = request.getSession().getServletContext().getRealPath(path);
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }
}
